﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpLocalizer.Common.DbApi;
using SpLocalizer.Common;
using System.Globalization;

namespace SpLocalizer.Common.Extensions
{
    public static class TranslationTaskExtensions
    {
        /// <summary>
        /// Load task data from the database
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public static BaseTranslationTask MakeAbstractTask(this TranslationTask task)
        {

            BaseTranslationTask taskToExport = null;
            try
            {
                taskToExport = ServiceContainer.Resolve<BaseTranslationTask>(task.TaskTypeProvider);
            }
            catch (Microsoft.Practices.Unity.ResolutionFailedException)
            { // looks like this project type wasn't loaded
                task.LocalizableContentReference.Load();
                task.LocalizableContent.ProjectReference.Load();
                Project taskProject = task.LocalizableContent.Project;
                
                AbstractTranslationProject.Open(taskProject.ProjectId);

                taskToExport = ServiceContainer.Resolve<BaseTranslationTask>(task.TaskTypeProvider);
            }

            taskToExport.FromLanguage = CultureInfo.GetCultureInfo(task.LcidFrom);
            taskToExport.ToLanguage = CultureInfo.GetCultureInfo(task.LcidTo);
            taskToExport.PropertiesSerializationXml = task.TaskTypeProviderData;
            taskToExport.TaskId = task.Id;
            taskToExport.SourceText = task.NtextValFrom;
            taskToExport.TranslatedText = task.NtextValTo;
            taskToExport.Status = (TranslationTaskStatus)task.Status;
            taskToExport.Format = task.Format;

            return taskToExport;
        }

        /// <summary>
        /// Load database task fields from Abstract task
        /// </summary>
        /// <param name="task"></param>
        /// <param name="AbstarctTask"></param>
        internal static void LoadFromAbstract(this TranslationTask task, BaseTranslationTask Task)
        {
            task.Id = Task.TaskId;
            task.LcidFrom = Task.FromLanguage.LCID;
            task.LcidTo = Task.ToLanguage.LCID;
            task.Status = (int)Task.Status;
            task.TaskTypeProvider = Task.TaskProviderName;
            task.TaskTypeProviderData = Task.PropertiesSerializationXml;
            task.Format = Task.Format;

            if (!String.IsNullOrEmpty(Task.SourceText))
            {
                task.NtextValFrom = Task.SourceText;
            }

            if (!String.IsNullOrEmpty(Task.TranslatedText))
            {
                task.NtextValTo = Task.TranslatedText;
            }

        }


 
    }
}
